package com.android.manghe.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.android.base.tools.SPUtil;
import com.android.manghe.config.SPTag;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

public class DeviceIdUtil {

    private static final String UUID_FILE_NAME = "qutu.info";

    /**
     * 保存文件到SD卡(写入SD卡需要权限，在AndroidManifest.xml中设置android.permission.WRITE_EXTERNAL_STORAGE)
     */
    private static String writeSD(String content) {
        //文件输出流
        FileOutputStream out = null;
        //设置文件路径
        File file = new File(Environment.getExternalStorageDirectory(), UUID_FILE_NAME);
        try {
            out = new FileOutputStream(file);
            out.write(content.getBytes());
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从SD卡中读取文件(读取SD卡需要权限，在AndroidManifest.xml中设置android.permission.READ_EXTERNAL_STORAGE)
     */
    private static String readSD() {
        //文件输入流
        FileInputStream in = null;
        //设置文件路径
        File file = new File(Environment.getExternalStorageDirectory(), UUID_FILE_NAME);
        try {
            in = new FileInputStream(file);
            //使用缓冲来读
            byte[] buf = new byte[1024];//每1024字节读一次
            StringBuilder builder = new StringBuilder();
            while (in.read(buf) != -1) {
                builder.append(new String(buf).trim());
            }
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 适配安卓10（Q）(API29)及以上
     *
     * @return
     */
    private static String getUUID(Context context) {
        String UUIDStr = SPUtil.get(context, SPTag.TAG_DeviceId, "").toString();
        if (UUIDStr.isEmpty()) {//如果为空或者空字符串就生成UUID创建文件并写入UUID
            UUIDStr = new Date().getTime() + "_" + UUID.randomUUID().toString();
            SPUtil.put(context, SPTag.TAG_DeviceId, UUIDStr);
        }
        return UUIDStr;
    }


    //获取手机的唯一标识
    public static String getPhoneSign(Context context) {
        StringBuilder deviceId = new StringBuilder();
        try {
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            @SuppressLint("MissingPermission")
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            @SuppressLint("MissingPermission")
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID(context);
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID(context));
        }
        return deviceId.toString();
    }

    public static String getUniqueId(Context context) {
        @SuppressLint("HardwareIds")
        // ANDROID_ID是设备第一次启动时产生和存储的64bit的一个数，当设备被wipe后该数重置。
                String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        @SuppressLint("HardwareIds")
        String id = androidID + Build.SERIAL; // +硬件序列号
//        try {
//            return toMD5(id);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return id;
//        }
        return id;
    }

    public static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString().substring(8, 24);
    }


}
